﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LuctecWS.DAL;
using System.Runtime.Serialization;
using LuctecWS.Aspect;

namespace LuctecWS.Core
{
    [DataContract]
    public class EmailTemplate : Base
    {
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Body { get; set; }
        [DataMember]
        public bool Active { get; set; }

        [LogException]
        public static List<EmailTemplate> GetTemplates()
        {
            using (LuctecEntities context = new LuctecEntities())
            {
                var emailtemplates = context.emailtemplates.ToList();

                return AdaptDBCore(emailtemplates);
            }
        }

        [LogException]
        public EmailTemplate Save()
        {
            using (LuctecEntities context = new LuctecEntities())
            {
                if (Id == 0)
                {
                    var emailtemplate = new emailtemplates() { Active = true, Body = this.Body, Name = this.Name, Id = this.Id };

                    context.AddObject("emailtemplates", emailtemplate);
                }
                else
                {
                    var emailtemplate = context.emailtemplates.First(et => et.Id == Id);

                    emailtemplate.Name = Name;
                    emailtemplate.Body = Body;
                    emailtemplate.Active = Active;
                }

                context.SaveChanges();

                if(Id == 0)
                    return AdaptDBCore(context.emailtemplates.ToList().Last());
                else
                    return AdaptDBCore(context.emailtemplates.ToList().First(et => et.Id == Id));
            }
        }

        [LogException]
        private static List<EmailTemplate> AdaptDBCore(List<emailtemplates> emailtemplates)
        {
            List<EmailTemplate> emailTemplates = new List<EmailTemplate>();

            if (emailtemplates != null)
            {
                foreach (var emailtemplate in emailtemplates)
                {
                    EmailTemplate emailTemplate = AdaptDBCore(emailtemplate);

                    if(emailtemplate != null)
                        emailTemplates.Add(emailTemplate);
                }
            }

            return emailTemplates;
        }

        [LogException]
        private static EmailTemplate AdaptDBCore(emailtemplates emailtemplate)
        {
            if (emailtemplate != null)
                return new EmailTemplate() { Active = emailtemplate.Active, Body = emailtemplate.Body, Id = emailtemplate.Id, Name = emailtemplate.Name };

            return null;
        }
    }
}